package br.com.fa7.controller;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

import br.com.fa7.service.ManagementFight;

@WebServlet("/event")
public class EventController extends WebSocketServlet {

	private static final long serialVersionUID = 1L;
	private ManagementFight managementFight = new ManagementFight();

	@Override
	protected StreamInbound createWebSocketInbound(String subProtocol,
			HttpServletRequest request) {
		
		Thread treadFight = new Thread(managementFight);
		treadFight.start();
		
		return new MessageInbound() {
			@Override
			protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
			}

			@Override
			protected void onTextMessage(CharBuffer arg0) throws IOException {
				while(true){
					if(managementFight.hasNewEvent()){
						WsOutbound outbound = getWsOutbound();
						try {
							outbound.writeTextMessage(CharBuffer.wrap(managementFight.getCurrentFightStatus()));
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		};
	}

}
